package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.UserMapper;
import aiku.numericalcontroloa.Model.Dto.UserDto;
import aiku.numericalcontroloa.Model.Entity.BaseEntity;
import aiku.numericalcontroloa.Model.Entity.User;
import aiku.numericalcontroloa.Model.Vo.ExaminePageVo;
import aiku.numericalcontroloa.Model.Vo.ExamineVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import aiku.numericalcontroloa.Model.Entity.Examine;
import aiku.numericalcontroloa.Service.ExamineService;
import aiku.numericalcontroloa.Mapper.ExamineMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author 马
* @description 针对表【examine】的数据库操作Service实现
* @createDate 2024-03-18 13:26:18
*/
@Service
public class ExamineServiceImpl extends ServiceImpl<ExamineMapper, Examine>
    implements ExamineService{
    @Autowired
    private ExamineMapper examineMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result examineList() {

        //TODO 权限还未做
        //先查询所有用户信息
//        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        List<User> userList = userMapper.selectList(null);
        ExaminePageVo examinePageVo = new ExaminePageVo();
        if (userList.size()<1){
            return Result.success(examinePageVo);
        }
        //这是有数据的用户信息
        //然后拿到用户id 去查询审核员信息
        List<String> userIdList = userList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        List<Examine> examineList = examineMapper.selectList(new LambdaQueryWrapper<Examine>().in(Examine::getUserId, userIdList));
        if (examineList.isEmpty()){
            return Result.success(examinePageVo);
        }
        List<String> financeIdlist = examineList.stream().map(Examine::getFinanceId).collect(Collectors.toList());
        List<String> managementIdlist = examineList.stream().map(Examine::getManagementId).collect(Collectors.toList());
        //把两个list合并成
        List<String> mergedList = new ArrayList<>();
        mergedList.addAll(financeIdlist);
        mergedList.addAll(managementIdlist);
        //查询用户信息
        List<User> userlist = userMapper.selectList(new LambdaQueryWrapper<User>().in(User::getId, mergedList));
        if(userlist.isEmpty()){
            List<String> collect = examineList.stream().map(Examine::getUserId).collect(Collectors.toList());
            List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>().in(User::getId, collect));
            Map<String, User> userMap = users.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));
            List<ExamineVo> arrayList = new ArrayList<>();
            for (Examine ex : examineList) {
                ExamineVo examineVo = new ExamineVo();
                examineVo.setExamineId(ex.getExamineId());
                examineVo.setUserName(userMap.get(ex.getUserId()).getNickName());
                examineVo.setUserId(ex.getUserId());
                arrayList.add(examineVo);
            }
            examinePageVo.setList(arrayList);
            examinePageVo.setTotal((long) userList.size());
            return Result.success(examinePageVo);
        }
        Map<String, User> userMap = userlist.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));

        Map<String, Examine> examineMap = examineList.stream().collect(Collectors.toMap(Examine::getUserId, Function.identity()));
        List<ExamineVo> arrayList = new ArrayList<>();
        for (User user : userList) {
            ExamineVo examineVo = new ExamineVo();
            Examine examine = examineMap.get(user.getId());
            examineVo.setUserName(user.getNickName());
            BeanUtils.copyProperties(examine, examineVo);
            User m1 = userMap.get(examine.getFinanceId());
            if(m1!=null){
                examineVo.setFinanceName(m1.getNickName());
            }
            User m2 = userMap.get(examine.getManagementId());
            if (m2!=null){
                examineVo.setManagementName(m2.getNickName());
            }
            arrayList.add(examineVo);
        }
        examinePageVo.setList(arrayList);
        examinePageVo.setTotal((long) userList.size());
        return Result.success(examinePageVo);
    }

    /**
     * 修改审核员信息
     * @param examineVo
     * @return
     */
    @Override
    public Result examineUpdate(ExamineVo examineVo) {
        // TODO 权限还未做
        Examine examine = examineMapper.selectById(examineVo.getExamineId());
        if (examine==null){

        }
        BeanUtils.copyProperties(examineVo, examine);
        examineMapper.updateById(examine);
        return Result.success("保存成功");
    }

    /**
     * 根据类型查询相关审核员信息
     * @param type
     * @return
     */
    @Override
    public Result examineByType(String type) {
        //TODO 权限还未做
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getRoleId, type));
        return Result.success(userList);
    }

    /**
     * 通过用户id查询审核员信息
     */
    public  Examine getExamine(String id){
        LambdaQueryWrapper<Examine> wrapper = new LambdaQueryWrapper<Examine>().eq(Examine::getUserId, id);
        return examineMapper.selectOne(wrapper);
    }

    @Override
    public Result getExamineList(UserDto userDto) {
        if (userDto == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数为空(userDto is null)");
        }
        if (userDto.getCurrentPage() == null || userDto.getPageSize() == null){
            return new Result(HttpStatus.BAD_REQUEST,"分页参数为空");
        }
        Page<Examine> examinePage = new Page<>(userDto.getCurrentPage(),userDto.getPageSize());
        // 条件查询
        LambdaQueryWrapper<Examine> examineLQW = new LambdaQueryWrapper<>();
        if (userDto.getId() != null && !userDto.getId().isEmpty()){
            examineLQW.eq(Examine::getUserId,userDto.getId());
        }
        List<Examine> examineList = examineMapper.selectPage(examinePage, examineLQW).getRecords();
        List<ExamineVo> examineVoList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        if (examineList.isEmpty()){
            map.put("total",examinePage.getTotal());
            map.put("examineVoList",examineVoList);
            return Result.success(map);
        }
        // 查用户
        Set<String> userIdList = examineList.stream().map(Examine::getUserId).collect(Collectors.toSet());
        // 查审核财务
        List<String> financeIdList = examineList.stream().map(Examine::getFinanceId).filter(Objects::nonNull).collect(Collectors.toList());
        // 查厂长
        List<String> managementIdList = examineList.stream().map(Examine::getManagementId).filter(Objects::nonNull).collect(Collectors.toList());
        userIdList.addAll(financeIdList);
        userIdList.addAll(managementIdList);
        List<User> userList = userMapper.selectBatchByIdWithDelete(userIdList);
        // 根据userId获取user对象
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        for (Examine examine : examineList){
            ExamineVo examineVo = new ExamineVo();
            BeanUtils.copyProperties(examine,examineVo);
            User user = userMap.get(examine.getUserId());
            examineVo.setUserName(user.getNickName());
            if (examine.getFinanceId() != null && !examine.getFinanceId().equals("")){
                User finance = userMap.get(examine.getFinanceId());
                examineVo.setFinanceName(finance.getNickName());
            }
            if (examine.getManagementId() != null && !examine.getManagementId().equals("")){
                User management = userMap.get(examine.getManagementId());
                examineVo.setManagementName(management.getNickName());
            }
            examineVoList.add(examineVo);
        }
        map.put("total",examinePage.getTotal());
        map.put("examineVoList",examineVoList);
        return Result.success(map);
    }
}




